

package dao

import (
	"errors"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/frame/gmvc"
	"guli-shopping/product-service/protobuff/productProto"
)

var (
	 //直接填充,this里也能用
	 PmsCategoryBrandRelationDao = &pmscategorybrandrelationDao{
		 M:g.DB().Table("pms_category_brand_relation").Safe(),
	 }
)

type pmscategorybrandrelationDao struct {
	gmvc.M
}

func (this *pmscategorybrandrelationDao) FindAll(query *productProto.PmsCategoryBrandRelationQuery) ([]*productProto.PmsCategoryBrandRelation,int,error) {
    //分页,如果要添加条件,在这里添加
    count, _ := this.OmitEmpty().Count()
	all, err := this.OmitEmpty().Page(int(query.Page), int(query.Size)).All()
	models := []*productProto.PmsCategoryBrandRelation{}
	err = all.Structs(&models)
	if err != nil {
		return nil,0,errors.New("查询失败")
	}
	return models,count,err

}

func (this *pmscategorybrandrelationDao) FindById(id int64) (*productProto.PmsCategoryBrandRelation,error) {
	all, err := this.WherePri(id).FindOne()
	if err != nil {
		return nil,errors.New("查询失败")
	}
	models := &productProto.PmsCategoryBrandRelation{}
	all.Struct(models)
	return models,err
}

func (this *pmscategorybrandrelationDao) Delete(ids[]int64) error {

	all, _ := this.WherePri(ids).Count()
	//要删除的数量不匹配
	if  len(ids)!=all{
		return errors.New("删除失败")
	}
	_, err := this.WherePri(ids).Delete()
	return err
}

func (this *pmscategorybrandrelationDao) Update(req *productProto.PmsCategoryBrandRelation) error {
	_, err := this.OmitEmpty().WherePri(req.Id).Data(req).Update()
	return err
}
func (this *pmscategorybrandrelationDao) Save(req []*productProto.PmsCategoryBrandRelation) (error) {

	all, err := this.Data(req).Save()
	if err!=nil {
		return errors.New("保存失败"+err.Error())
	}
	count, _ := all.RowsAffected()
	if count<=0 {
		return errors.New("保存失败,可能是重复保存")
	}
	return nil
}

func (this *pmscategorybrandrelationDao) FindAllByBrandId(id int64) ([]*productProto.PmsCategoryBrandRelation,error) {
	all, err := this.Where("brand_id", id).All()
	models := []*productProto.PmsCategoryBrandRelation{}
	err = all.Structs(&models)
	if err != nil {
		return nil,errors.New("查询失败")
	}
	return models,nil
}




